<template>
    <div>
        <div class="container">
            <div class="container_title">报销费用汇总信息</div>
            <div class="container_content">
                <el-table
                    :data="infoData.businessInfoGroupVos || []"
                    :span-method="arraySpanMethod"
                    border
                    style="width: 100%"
                    show-summary
                    :summary-method="getSummaries"
                >
                    <el-table-column
                        label="业务类型"
                        width="180"
                        align="center"
                    >
                        <template slot-scope="scope">
                            {{
                                scope.row.businessType
                                    | filterBusinessType(dicts.BusinessType)
                            }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="costType"
                        label="费用类型"
                        align="center"
                    >
                        <template slot-scope="scope">
                            <dict-tag
                                v-if="!!scope.row.__dict"
                                :options="dict.type[scope.row.__dict]"
                                :value="scope.row.costType"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="money"
                        label="单项费用"
                        align="center"
                    >
                        <template slot-scope="scope">
                            {{ format_thousand(scope.row.money) || 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="expenseMoney"
                        label="金额"
                        align="center"
                    >
                        <template slot-scope="scope">
                            {{ format_thousand(scope.row.expenseMoney) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="value5"
                        label="是否支付"
                        align="center"
                    >
                        <template slot-scope="scope">
                            {{
                                scope.row.payFlag
                                    | filterNeedpayType(dicts.needpayType)
                            }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="value5"
                        label="备注"
                        align="center"
                        min-width="200px"
                    >
                        <template slot-scope="scope">
                            <el-input
                                v-if="state == 'write'"
                                :disabled="state !== 'write'"
                                type="textarea"
                                v-model="scope.row.remark"
                                placeholder=""
                                :show-word-limit="false"
                                :autosize="{ minRows: 2, maxRows: 2 }"
                                resize="none"
                                @change="setRemake(scope.row)"
                            >
                            </el-input>
                            <span v-else>
                                {{ scope.row.remark || "-" }}
                            </span>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- <div class="remake"> -->
                <!-- <div class="label">附言：</div> -->
                <!-- <div class="content"> -->
                <!-- <el-input -->
                <!-- v-if="state == 'write'" -->
                <!-- :disabled="state !== 'write'" -->
                <!-- type="textarea" -->
                <!-- v-model="infoData.remake" -->
                <!-- placeholder="" -->
                <!-- :show-word-limit="false" -->
                <!-- :autosize="{ minRows: 4, maxRows: 4 }" -->
                <!-- resize="none" -->
                <!-- > -->
                <!-- </el-input> -->
                <!-- <span v-else> -->
                <!-- {{ infoData.remake || "-" }} -->
                <!-- </span> -->
                <!-- </div> -->
                <!-- </div> -->
            </div>
        </div>
    </div>
</template>

<script>
import * as apis from "@/api/finance/reimburs/preview/api.js";
export default {
    name: "",
    props: {
        value: {
            required: true,
            default: () => {
                return {};
            },
        },

        state: {
            default: "write",
        },
    },
    dicts: [
        "expense_use_type",
        "expense_use_type_car",
        "expense_use_type_pay",
        "expense_use_type_transport",
        "expense_use_type_registration",
        "expense_use_type_other",
        "expense_use_type_gps",
        "expense_business_cleancar",
        "expense_business_fuel",
        "expense_business_stopcar",
        "expense_business_road",
        "expense_business_car",
        "expense_business_pay",
        "expense_business_transport",
        "expense_business_registration",
        "expense_business_inspect",
        "expense_business_gps",
        "expense_business_other",
    ],

    data() {
        return {
            dicts: {
                // 收款人类型
                payeeTypeList: [
                    {
                        label: "员工",
                        value: "1",
                    },
                    {
                        label: "司机",
                        value: "2",
                    },
                    {
                        label: "供应商",
                        value: "3",
                    },
                ],
                contractTypeList: [
                    {
                        label: "短租",
                        value: "1",
                    },
                    {
                        label: "渠道",
                        value: "2",
                    },
                    {
                        label: "自营",
                        value: "3",
                    },
                    {
                        label: "代收代付",
                        value: "4",
                    },
                ],

                needpayType: [
                    {
                        label: "是",
                        value: "1",
                    },
                    {
                        label: "否",
                        value: "2",
                    },
                ],
                BusinessType: [],
            },
        };
    },
    computed: {
        infoData: {
            get() {
                return this.value;
            },
            set(val) {
                this.$emit("input", val);
            },
        },
    },
    watch: {
        infoData: {
            deep: true,
            handler(val) {
                if (val?.businessInfoGroupVos?.length > 0) {
                    this.formatValue();
                }
            },
            immediate: true,
        },
    },
    filters: {
        filterBusinessType: (row, dict) => {
            if (!row) return "-";
            let ele = dict.find((item) => {
                return item.index == row;
            });
            return ele?.value ?? "-";
        },
        filterNeedpayType(row, dict) {
            if (!row) return "-";
            let ele = dict.find((item) => {
                return item.value == row;
            });
            return ele?.label ?? "-";
        },
    },
    created() {},
    mounted() {
        this.getBusinessType();
    },

    methods: {
        setRemake(row, $index) {
            let items = this.infoData?.businessInfoGroupVos.filter(
                (item, index) => {
                    if (
                        index !== $index &&
                        item.businessType == row.businessType
                    ) {
                        return true;
                    }
                }
            );
            items.forEach((item) => {
                item.remark = row.remark;
            });
        },
        async getBusinessType() {
            return new Promise((resolve, reject) => {
                this.loading = true;
                let params = {};
                apis?.BusinessType(params)
                    .then((res) => {
                        this.dicts.BusinessType = res.data;
                        this.formatValue();
                    })
                    .catch((err) => {})
                    .finally(() => {
                        this.loading = false;
                        resolve();
                    });
            });
        },

        audit() {
            this.$modal.loading("正在保存...");
            let params = [];
            this.infoData?.businessInfoGroupVos?.map((item) => {
                params.push({
                    id: item.id,
                    remark4: item.remark4,
                });
            });

            apis?.Audit(params)
                .then((res) => {
                    if (res.code == 200) {
                        this.$message.success("保存成功");
                        const obj = this.$route;
                        this.$tab.closeOpenPage(obj).then(() => {
                            this.$router.push({
                                path: "/finance/reimburs",
                            });
                        });
                    }
                })
                .finally((res) => {
                    this.$modal.closeLoading();
                });
        },
        formatValue() {
            if (!this.infoData) return;
            this.formatTableSpan(
                this?.infoData?.businessInfoGroupVos,
                "businessType"
            );
            this.infoData?.businessInfoGroupVos?.forEach((item) => {
                let ele = this.dicts?.BusinessType?.find((e) => {
                    return e.index?.toString() == item.businessType?.toString();
                });
                if (!Reflect.has(item, "__dict") || !item.__dict) {
                    // item.__dict = ele?.dictType;
                    this.$set(item, "__dict", ele?.dictType);
                }
            });
        },
        formatTableSpan(data, key) {
            if (Object.prototype.toString.call(data) !== "[object Array]") {
                throw new Error("arguments[0] not is a Array");
            }
            if (data.length <= 1) return;
            let targetIndex = 0;
            key ??= "error";
            if (key == "error") throw new Error("can't get prop");
            data.forEach((item, index) => {
                if (index == targetIndex) {
                    let len = data.findLastIndex((e) => e[key] == item[key]);
                    item.__col = len - targetIndex + 1;
                    targetIndex = len + 1;
                } else if (index < targetIndex) {
                    item.__col = 0;
                }
            });
        },
        arraySpanMethod({ row, column, rowIndex, columnIndex }) {
            if (
                columnIndex == 0 ||
                columnIndex == 3 ||
                columnIndex == 5 ||
                columnIndex == 6
            ) {
                if (Reflect.has(row, "__col")) {
                    if (row?.__col) {
                        return [row.__col, 1];
                    } else {
                        return [0, 0];
                    }
                } else {
                    return [1, 1];
                }
            } else {
                return [1, 1];
            }
        },
        getSummaries({ columns, data }) {
            let sum = [];
            columns.forEach((element, index) => {
                if (index == 0) {
                    element.colSpan = columns.length - 1;
                } else if (index == 1) {
                    element.colSpan = 1;
                }
            });
            sum.push("合计");
            sum.push(this.format_thousand(this.infoData?.sumMoney) ?? 0);
            return sum;
        },
        getDateDuration(startTime, endTime) {
            let result = "-";
            let start = this.$dayjs(startTime);
            let end = this.$dayjs(endTime);
            let duration = this.$dayjs.duration(end.diff(start));
            let H_all = duration.as("hours");
            let D = parseInt(H_all / 24);
            let H = (H_all % 24).toFixed(1)?.split(".");
            if (D == 0) {
                result = `${H} 小时`;
            } else if ((H?.[0] == 0 && H?.[1] == 0) || (!H[0] && !H[1])) {
                result = `${D} 天`;
            } else if (H?.[1] == 0) {
                result = `${D} 天 ${H[0]} 小时`;
            } else {
                result = `${D} 天 ${H[0]}.${H[1]} 小时`;
            }
            return result;
        },
    },
};
</script>
<style scoped lang="scss">
.container {
    border-radius: 10px;
    background-color: #fff;
    // margin: 20px;
    padding: 20px;
    .container_title {
        margin-bottom: 30px;
        border-bottom: 1px solid #e9e9e9;
        font-weight: 600;
        display: flex;
        justify-content: space-between;
        padding-bottom: 15px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 500;
        font-size: 16px;
        color: #333333;
        line-height: 22px;
        text-align: left;
        font-style: normal;
    }
    .container_content {
        // padding: 20px;
    }
}
.chunk_nav {
    background-color: #fff;
    // padding: 20px 0;
    .nav_item {
        padding-bottom: 30px;
        display: flex;

        .label {
            width: 250px;
            text-align: right;
            padding-right: 25px;
            box-sizing: border-box;
        }
        .content {
            flex: 1;
            min-width: 0;
            padding-right: 50px;
            .menu {
                display: grid;
                grid-template-columns: repeat(6, 1fr);
                gap: 5px 0;
            }
        }
    }
}
.chunk_contentBox {
    background-color: #fff;
    // padding: 25px;
    .chunk {
        margin-bottom: 50px;
    }
}
::v-deep .gridBox {
    padding-top: 0;
}

.component-fade-enter, .component-fade-leave-to
/* .component-fade-leave-active for below version 2.1.8 */ {
    transform: translateX(100px);
    opacity: 0;
}

.component-fade-enter-active,
.component-fade-leave-active {
    transition: all 0.8s;
}
// ::v-deep .el-table__footer {
//     tr:first-child {
//         td:first-child {
//             .cell {
//                 text-align: left;
//             }
//         }
//     }
// }
.remake {
    margin-top: 15px;
    display: flex;
    .content {
        flex: 1;
    }
}
.handleBox {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
}
</style>
